<template>
    <a-card title="修改订单">
        <OrderForm ref="formRef" v-model:value="formState"></OrderForm>

        <div class="bottom-div">
            <a-space>
                <a-button @click="save" :loading="loading" size="large" type="primary">保存</a-button>
                <a-button @click="close" size="large">取消</a-button>
            </a-space>
        </div>
    </a-card>
</template>
<script setup lang="ts">
import { ref, onActivated, onMounted } from 'vue'

import OrderForm from './orderForm.vue'
import { useRouter } from "vue-router"
import { useTabStore } from '@/stores/tab'
import type { Order } from '@/types/Order'

import { getOrderDetail, putOrder } from '@/api/orderApi'
import { message } from 'ant-design-vue'
import { useOrderStore } from '@/stores/order'
import { amapGeo } from '@/api/amapApi'
const orderStore = useOrderStore()
const tabStore = useTabStore()
const router = useRouter()
const formState = ref<Order>({ orderGoodsList: [], project: {} })
const formRef = ref()
const loading = ref(false)

const save = async () => {
    loading.value = true


    try {
        await formRef.value.validate()
        formState.value.amount = 0
        for(let item of formState.value.orderGoodsList!){
            formState.value.amount += item.goodsNum * item.goodsPrice / 100
        }
        let res = await putOrder(formState.value)



        message.success('修改成功')
        orderStore.reloadList = true
        close()

    } catch (error) {

    }
    loading.value = false

}

const close = () => {
    router.back()
    tabStore.removeTab(router.currentRoute.value.fullPath)
}

onActivated(async () => {
    let res = await getOrderDetail(orderStore.updateOrder.id!)
    res.data.orderGoodsList = []
    for(let item of res.data.goodsList!){
        res.data.orderGoodsList.push({
            goodsId: item.id,
            goodsNum: item.num,
            goodsPrice: item.price,
            goodsName: item.name
        })
    }
    formState.value = res.data
})
</script>
<style scoped>
.bottom-div {
    padding: 30px 0;
    text-align: center;
}
</style>